package org.apache.lucene.index;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.store.Directory;

public class TagIndexWriter {
  private Map<Term,Posting> postings = new HashMap<Term,Posting>();
  Directory directory;
  String segment;
  TagFieldInfos fis;
  int indexInterval;
  
  public TagIndexWriter(Directory directory, String segment, TagFieldInfos fis, int indexInterval) {
    this.directory = directory;
    this.segment = segment;
    this.fis = fis;
    this.indexInterval = indexInterval;
  }
  
  public void add(Term term, int doc) {
    Posting posting = postings.get(term);
    if (posting == null) {
      posting = new Posting(term);
      postings.put(term, posting);
    }
    posting.docs.add(doc);
  }
  
  public static class Posting implements Comparable {
    private Term term;
    private List<Integer> docs = new ArrayList<Integer>();
    
    public Posting(Term term) {
      this.term = term;
    }
    
    public int compareTo(Object object) {
      Posting other = (Posting)object;
      return term.compareTo(other.term);
    }
  }
  
  public void close() throws IOException {
    List<Posting> sorted = new ArrayList<Posting>(postings.values());
    Collections.sort(sorted);
    TagTermInfosWriter tagTermInfosWriter = new TagTermInfosWriter(directory, segment, fis, indexInterval);
    for (int x=0; x < sorted.size(); x++) {
      Posting posting = sorted.get(x);
      TagTermInfo ti = new TagTermInfo();
      ti.docFreq = posting.docs.size();
      ti.termNum = x;
      int[] array = new int[posting.docs.size()];
      for (int i=0; i < array.length; i++) {
        array[i] = posting.docs.get(i);
      }
      Arrays.sort(array); // should already be sorted
      tagTermInfosWriter.add(posting.term, x, array);
    }
    tagTermInfosWriter.close();
  }
  
  public void addDocument(int docNum, Document document) {
    List fields = document.getFields();
    for (int x=0; x < fields.size(); x++) {
      Field field = (Field)fields.get(x);
      Term term = new Term(field.name(), field.stringValue());
      add(term, docNum);
    }
  }
}
